<style>
    #query_tables_area{
        background-color: #d8eaed;
        margin-top: 5px;
        margin-bottom: 5px;
        padding-top: 10px;
        padding-bottom: 10px;
        padding-left: 10px;
        padding-right: 10px;
    }

    .query_on_clause_text_span{
        color: #c77405;
        font-size: medium;
        margin-left: 20px;
    }
    .query_column_area_one_column{
        float: none;
    }
    .create_button{
        background-color: #E5E5E5;
    }

</style>

<script type="text/javascript" >

    var db_table_info =<?= $this->db_table_json_info ?>

    $(document).ready(function() {

        showAction();

        $('#action_select').change(function() {
            showAction();
        });

        $('#create_class_bt').click(function() {
            create_class();
            return false;
        });

        $('#create_query_bt').click(function() {
            create_query();
            return false;
        });

        $('#create_update_bt').click(function() {
            create_update();
            return false;
        });

        $('#create_delete_bt').click(function() {
            create_delete();
            return false;
        });


        $('#create_insert_bt').click(function() {
            create_insert();
            return false;
        });

        $('#create_definitions_bt').click(function() {
            create_definitions();
            return false;
        });






        $('#create_pdo_handle_bt').click(function() {
            create_pdo();
            return false;
        });
        
        $('.query_table_alias').live("change",function(){
            var id=$(this).attr('id').replace(/query_table_alias_id_/g,'');
            if(typeof query_cache_data.line_id_table_column_map[id] !== "undefined"){
                delete  query_cache_data.line_id_table_column_map[id];
            }
        });

        loadSetting();

        prepareTablesInfo();

        initQuerySelectTableFirstLine();
        initSelectTableEvent();

        prepareSelectColumnDialog();
        prepareSelectOrderByColumnDialog();
        prepareConditionEditDilog();
    });


    var uid_column_map = {};
    function prepareSelectOrderByColumnDialog() {
        //select_columns_dialog

        $('#order_by_select_columns_dialog').dialog({
            autoOpen: false,
            modal: true,
            buttons: [
                {
                    text: "Save",
                    click: function() {
                        $(this).dialog("close");

                        selectColumnDialogSave4OrderBy();

                    }
                },
                {
                    text: "Close",
                    click: function() {
                        $(this).dialog("close");
                    }
                }
            ],
            width: 800,
            height: 600,
            title: 'Column Pickup'
        });
        $('#query_order_by_add_bt').click(function() {


            var uuid = "add_order_by_column_area_bt";


            var columns = getUidColumnsList(uuid, null);

            if (columns === null) {
                return false;
            }

            var showColumn = [];
            query_cache_data.columns = {};
            for (var ind in columns) {
                var one = columns[ind];
                var obj = {
                    display: (one.column.talias !== '' ? one.column.talias + "." : "") + one.column.name,
                    id: one.uuid,
                    type: one.column.type

                };
                showColumn.push(obj);

                query_cache_data.columns[one.uuid] = obj;
            }

            $('#order_by_select_columns_holder').init_item_table_pickup(
                    {
                        input_type: 'radio', //required
                        column_size: 2, //optional
                        line_size: 2, //optional, if column_size is gaven, this will be ignor.
                        odd_column_class: 'odd_column', //optional
                        even_column_class: 'even_column', //optional
                        odd_line_class: 'odd_line', //optional
                        even_line_class: 'even_line', //optional
                        table_id: 'table_id',
                        table_class: 'table_class',
                        caption: 'Add One Order BY Column',
                        item_name: 'order_by_radio',
                        data: showColumn, //requried
                        selected_values: ['vvv', 'asdf']
                    }
            );

            $('#order_by_select_columns_dialog').dialog('open');
        });
    }
    function prepareSelectColumnDialog() {
        //select_columns_dialog

        $('#select_columns_dialog').dialog({
            autoOpen: false,
            modal: true,
            buttons: [
                {
                    text: "Select All",
                    click: function() {
                        $('#select_columns_holder input[type="checkbox"]').prop("checked", true);
                    }
                },
                {
                    text: "De-Select All",
                    click: function() {
                        $('#select_columns_holder input[type="checkbox"]').prop("checked", false);
                    }
                },
                {
                    text: "Save",
                    click: function() {
                        $(this).dialog("close");

                        selectColumnDialogSave();

                    }
                },
                {
                    text: "Close",
                    click: function() {
                        $(this).dialog("close");
                    }
                }
            ],
            width: 800,
            height: 600,
            title: 'Column Pickup'
        });

        $('#query_column_area_bt').click(function() {


            var uuid = "query_column_area_bt";


            var columns = getUidColumnsList(uuid, null);

            if (columns === null) {
                return false;
            }

            var showColumn = [];
            query_cache_data.columns = {};
            for (var ind in columns) {
                var one = columns[ind];
                var obj = {
                    display: (one.column.talias !== '' ? one.column.talias + "." : "") + one.column.name,
                    id: one.uuid,
                    type: one.column.type

                };
                showColumn.push(obj);

                query_cache_data.columns[one.uuid] = obj;
            }

            $('#select_columns_holder').init_item_table_pickup(
                    {
                        input_type: 'checkbox', //required
                        column_size: 2, //optional
                        line_size: 2, //optional, if column_size is gaven, this will be ignor.
                        odd_column_class: 'odd_column', //optional
                        even_column_class: 'even_column', //optional
                        odd_line_class: 'odd_line', //optional
                        even_line_class: 'even_line', //optional
                        table_id: 'table_id',
                        table_class: 'table_class',
                        caption: 'Select Columns',
                        item_name: 'radio_name',
                        data: showColumn, //requried
                        selected_values: ['vvv', 'asdf']
                    }
            );
            column_select_target = "query";
            $('#select_columns_dialog').dialog('open');
        });


        $('#update_column_area_bt').click(function() {


            var uuid = "update_column_area_bt";


            var columns = getUidColumnsList(uuid, null);

            if (columns === null) {
                return false;
            }

            var showColumn = [];
            query_cache_data.columns = {};
            for (var ind in columns) {
                var one = columns[ind];
                var obj = {
                    display: (one.column.talias !== '' ? one.column.talias + "." : "") + one.column.name,
                    id: one.uuid,
                    type: one.column.type

                };
                showColumn.push(obj);

                query_cache_data.columns[one.uuid] = obj;
            }

            $('#select_columns_holder').init_item_table_pickup(
                    {
                        input_type: 'checkbox', //required
                        column_size: 2, //optional
                        line_size: 2, //optional, if column_size is gaven, this will be ignor.
                        odd_column_class: 'odd_column', //optional
                        even_column_class: 'even_column', //optional
                        odd_line_class: 'odd_line', //optional
                        even_line_class: 'even_line', //optional
                        table_id: 'table_id',
                        table_class: 'table_class',
                        caption: 'Update Columns',
                        item_name: 'radio_name',
                        data: showColumn, //requried
                        selected_values: ['vvv', 'asdf']
                    }
            );
            column_select_target = 'update';
            $('#select_columns_dialog').dialog('open');
        });

        $('#insert_column_area_bt').click(function() {


            var uuid = "insert_column_area_bt";


            var columns = getUidColumnsList(uuid, null);

            if (columns === null) {
                return false;
            }

            var showColumn = [];
            query_cache_data.columns = {};
            for (var ind in columns) {
                var one = columns[ind];
                var obj = {
                    display: (one.column.talias !== '' ? one.column.talias + "." : "") + one.column.name,
                    id: one.uuid,
                    type: one.column.type


                };
                showColumn.push(obj);

                query_cache_data.columns[one.uuid] = obj;
            }

            $('#select_columns_holder').init_item_table_pickup(
                    {
                        input_type: 'checkbox', //required
                        column_size: 2, //optional
                        line_size: 2, //optional, if column_size is gaven, this will be ignor.
                        odd_column_class: 'odd_column', //optional
                        even_column_class: 'even_column', //optional
                        odd_line_class: 'odd_line', //optional
                        even_line_class: 'even_line', //optional
                        table_id: 'table_id',
                        table_class: 'table_class',
                        caption: 'Insert Columns',
                        item_name: 'radio_name',
                        data: showColumn, //requried
                        selected_values: ['vvv', 'asdf']
                    }
            );
            column_select_target = 'insert';
            $('#select_columns_dialog').dialog('open');
        });


    }
    var column_select_target;
    function selectColumnDialogSave() {
        if (column_select_target === 'query') {
            selectColumnDialogSave4Query();
        }
        else if (column_select_target === 'update') {
            selectColumnDialogSave4Update();
        }
        else if (column_select_target === 'insert') {
            selectColumnDialogSave4Insert();
        }

    }
    function selectColumnDialogSave4OrderBy() {
        var selectColumnUid = null;

        $('#order_by_select_columns_holder input[type="radio"]').each(function() {

            if ($(this).prop('checked')) {
                selectColumnUid = $(this).attr('id');
            }
        });
        var html = "<div class='query_order_by_area_one_column'>";
        if ($('#order_by_column_user_variable_radio').prop('checked')) {

            var vn = $('#order_by_column_user_variable_name').val();
            html += "<span>User's Variable:" + vn + "</span>";



            var input = "<input class='query_order_by_column_variable' type='hidden' value='" + vn + "' >";
            input += "<input class='query_order_by_type' type='hidden' value='variable' >";
            input += "<input type='hidden'  id='query_order_by_column_type_" + one + "' value='" + info.type + "'>";

            html += input;
        }
        else {

            if (selectColumnUid === null) {
                //user do not select any column

                return;
            }



            var uidMap = query_cache_data.columns;



            var info = uidMap[selectColumnUid];

            var text = info.display;
            html += "<span>" + text + "</span>";



            var input = "<span> DESC</span><input type='checkbox' class='query_order_by_desc' id='query_order_by_desc_" + selectColumnUid + "' >";
            input += "<input class='query_order_by_column_id' type='hidden' value='" + selectColumnUid + "' >";
            input += "<input class='query_order_by_type' type='hidden' value='fixed' >";

            html += input;


        }
        html += "<button class='query_order_by_remove_bt'>delete</button>";

        html += "</div>";
        $('#query_ordery_by_area').append(html);


        $('.query_order_by_remove_bt').click(function() {

            $(this).parent().remove();
            return false;
        });

    }

    function selectColumnDialogSave4Query() {
        var selectColumnUid = [];

        $('#select_columns_holder input[type="checkbox"]').each(function() {

            if ($(this).prop('checked')) {
                selectColumnUid.push($(this).attr('id'));
            }
        });

        var html = "";

        var uidMap = query_cache_data.columns;

        for (var ind in selectColumnUid) {
            var one = selectColumnUid[ind];
            var info = uidMap[one];
            html += "<div class='query_column_area_one_column'>";
            var text = info.display;
            html += "<span>" + text + "</span>";

            var aliasVa = text.replace(/\./g, "_");

            var input = "<input type='text' size='60' id='column_alias_" + one + "' value='" + aliasVa + "'>";

            html += input;
            html += "<span>,</span>";

            html += "</div>";
        }

        $('#query_column_area_column_list').html(html);

    }
    function selectColumnDialogSave4Update() {
        var selectColumnUid = [];

        $('#select_columns_holder input[type="checkbox"]').each(function() {

            if ($(this).prop('checked')) {
                selectColumnUid.push($(this).attr('id'));
            }
        });

        var html = "";

        var uidMap = query_cache_data.columns;

        for (var ind in selectColumnUid) {
            var one = selectColumnUid[ind];
            var info = uidMap[one];
            html += "<div class='update_column_area_one_column'>";
            var text = info.display;
            html += "<span>" + text + "</span>";



            var input = "<input type='text' id='update_column_value_" + one + "' value='" + getVariableName(text) + "'>";
            input += "<input type='hidden'  id='update_column_type_" + one + "' value='" + info.type + "'>";

            html += input;

            html += "<input type='radio' name='update_column_value_type_" + one + "' value='pure' > Pure Value";
            html += "<input type='radio' name='update_column_value_type_" + one + "' value='variable' checked='checked'> Variable ";
            html += "<input type='radio' name='update_column_value_type_" + one + "' value='function'> Internal Function ";
            html += "<span>,</span>";

            html += "</div>";
        }

        $('#update_column_area_column_list').html(html);

    }

    function selectColumnDialogSave4Insert() {
        var selectColumnUid = [];

        $('#select_columns_holder input[type="checkbox"]').each(function() {

            if ($(this).prop('checked')) {
                selectColumnUid.push($(this).attr('id'));
            }
        });

        var html = "";

        var uidMap = query_cache_data.columns;

        for (var ind in selectColumnUid) {
            var one = selectColumnUid[ind];
            var info = uidMap[one];
            html += "<div class='update_column_area_one_column'>";
            var text = info.display;
            html += "<span>" + text + "</span>";



            var input = "<input type='text' id='insert_column_value_" + one + "' value='" + getVariableName(text) + "'>";
            input += "<input type='hidden'  id='insert_column_type_" + one + "' value='" + info.type + "'>";

            html += input;

            html += "<input type='radio' name='insert_column_value_type_" + one + "' value='pure' > Pure Value";
            html += "<input type='radio' name='insert_column_value_type_" + one + "' value='variable' checked='checked'> Variable ";
            html += "<input type='radio' name='insert_column_value_type_" + one + "' value='function'> Internal Function ";
            html += "<span>,</span>";
            html += "<input type='checkbox' name='insert_column_value_is_unique_" + one + "' value='1'> Is Uniqu Index ";
            html += "</div>";
        }

        $('#insert_column_area_column_list').html(html);

    }

    function prepareConditionEditDilog() {
        $('#condition_edit_dialog').dialog({
            autoOpen: false,
            modal: true,
            buttons: [
                {
                    text: "Save",
                    click: function() {
                        $(this).dialog("close");

                        onConditionDialogSave();

                    }
                },
                {
                    text: "Close",
                    click: function() {
                        $(this).dialog("close");
                    }
                }
            ],
            width: 800,
            height: 600,
            title: 'Condition Edit'
        });

        $('#query_where_claus_edit_bt').click(function() {
            var uuid = "query_where_claus_id";


            var columns = getUidColumnsList(uuid, null);
            if (columns === null) {
                return;
            }
            initConditionEditDialog(uuid, columns);
            return false;
        });


    }



    var current_editing_line_id = null;

    function initConditionEditDialog(lineId, columns) {

        var data = null;
        if (typeof query_cache_data.line_id_logic_map[lineId] !== 'undefined' &&
                typeof query_cache_data.line_id_logic_map[lineId]['logic_data'] !== 'undefined') {
            data = query_cache_data.line_id_logic_map[lineId]['logic_data'];
        }

        current_editing_line_id = lineId;
        current_editing_logic = new QueryLogic("condtion_edit_holder", data, columns);
        current_editing_logic.setResultTextId('condtion_review_text');
        current_editing_logic.logic_view_rendering();
        $('#condition_edit_dialog').dialog("open");

    }

    function onConditionDialogSave() {
        if (current_editing_logic === null || current_editing_line_id === null) {
            return;
        }

        query_cache_data.line_id_logic_map[current_editing_line_id] = {logic_data: current_editing_logic.data, logic_string: current_editing_logic.toConditionStr()};


        $('#query_on_clause_text_' + current_editing_line_id).text(current_editing_logic.toConditionStr());

    }

    var table_info = {};

    var table_number = 0;


    var used_alias = {};

    var alias_counter = 100;

    function prepareTablesInfo() {

        var tab_select_options = "<option value='NONE'>Please Select a Table</option>";
        table_number = 0;
        for (var db in db_table_info) {
            var tt = db_table_info[db];
            for (var tn in tt) {

                var tabFullName = db + "." + tn;
                var alias = db + "_" + tn;
                table_info[tabFullName] = {
                    detail: tt[tn],
                    alias: alias,
                    db: db,
                    name: tn
                };
                table_number++;

                tab_select_options += "<option value='" + tabFullName + "'>" + tabFullName + "</option>";
            }

        }

        $('#query_select_table_id_replace_123').html(tab_select_options);



    }

    function initQuerySelectTableFirstLine() {
        var html = $('#query_select_talbe_template_tr').html();

        var uid = getUUID();

        html = html.replace(/replace_123/g, uid);

        $('#query_select_tables').html(html);




        $('#query_select_join_method_id_' + uid).remove();
        $('#query_on_clause_div_id_' + uid).remove();


        if (table_number === 1) {
            $('#query_select_tables option').first().next().prop('selected', true);
        }

    }

    var used_alias_table_map = {};


    var query_cache_data;

    function resetQueryCache() {
        query_cache_data = {
            line_id_above_tables_map: {},
            line_id_table_column_map: {},
            line_id_table_name_array: [],
            global_uid_column_map: {},
            line_id_logic_map: {},
            columns: {}
        };
    }

    function initSelectTableEvent() {

        resetQueryCache();
        $('.query_select_table').live('change', function() {


            resetQueryCache();
            var tn = $(this).val();

            if (tn === 'NONE') {
                return;
            }

            var alias;
            if (typeof used_alias_table_map[tn] !== 'undefined') {
                // if user used this alias, let them use the same again

                alias = used_alias_table_map[tn];
            }
            else {

                if (table_number === 1) {
                    alias = '';
                }
                else {
                    alias = table_info[tn].alias;

                    if (typeof used_alias[alias] !== 'undefined') {
                        alias += alias + alias_counter;
                        alias_counter++;
                    }
                }
                used_alias[alias] = 1;
            }

            var uid = $(this).attr('id').replace(/query_select_table_id_/g, '');

            $('#query_table_alias_id_' + uid).val(alias);



        });

        $('.query_select_table_add_bt').live('click', function() {

            resetQueryCache();
            var html = $('#query_select_talbe_template_tr').html();

            var uid = getUUID();

            html = html.replace(/replace_123/g, uid);

            var myid = $(this).attr('id').replace(/query_select_table_add_bt_/g, '');


            $('#query_select_table_tr_' + myid).after(html);
            return false;

        });
        $('.query_select_table_delete_bt').live('click', function() {


            resetQueryCache();

            var myid = $(this).attr('id').replace(/query_select_table_delete_bt_/g, '');


            $('#query_select_table_tr_' + myid).remove();

            return false;


        });

        $('.query_on_clause').live('click', function() {




            //get this line's uuid from button's id

            var uuid = $(this).attr('id').replace(/query_on_clause_id_/g, '');



            var columns = getUidColumnsList(uuid, uuid);

            if (columns === null) {
                return;
            }
            initConditionEditDialog(uuid, columns);
        });
    }

    function getUidColumnsList(uuid, stopId) {


        var lineIdList;
        if (typeof query_cache_data.line_id_above_tables_map[uuid] === 'undefined') {

            //find above line id
            lineIdList = [];


            var stop = false;

            query_cache_data.line_id_table_name_array = [];
            $('#query_select_tables .query_select_table').each(function() {
                var suid = $(this).attr('id').replace(/query_select_table_id_/g, '');

                if (!stop) {
                    lineIdList.push(suid);
                }
                if (suid === stopId) {
                    stop = true;
                }
                query_cache_data.line_id_table_name_array.push({line_id: suid, table_full_name: $(this).val()});
            });

            query_cache_data.line_id_above_tables_map[uuid] = lineIdList;
        }
        else {
            lineIdList = query_cache_data.line_id_above_tables_map[uuid];
        }


        var columns = [];

        var ts = 0;
        for (var ind in lineIdList) {
            ts++;
        }

        for (var ind in lineIdList) {

            //check the alias is not empty

            var lineId = lineIdList[ind];
            var aid = "query_table_alias_id_" + lineId;


            var aliasName = $('#' + aid).val();


            if (aliasName === '' && ts > 1) {
                alert("alias is required");
                return null;
            }

            var uidColumnMap;

            if (typeof query_cache_data.line_id_table_column_map[lineId] !== 'undefined') {
                uidColumnMap = query_cache_data.line_id_table_column_map[lineId];
            }
            else {//create the cache

                var sid = "query_select_table_id_" + lineIdList[ind];
                var selectedTable = $('#' + sid).val();
                if (selectedTable === 'NONE') {
                    alert("you need select table before set on cluase");
                    return null;
                }
                uidColumnMap = {};

                var tableInfo = table_info[selectedTable];
                var tableInfoDetail = tableInfo.detail;

                for (var i3 in tableInfoDetail) {

                    var uuuid = getUUID();
                    var info = {
                        name: tableInfoDetail[i3].name,
                        table: tableInfo.name,
                        db: tableInfo.db,
                        uuid: uuuid,
                        line_uid: lineId,
                        type: tableInfoDetail[i3].type,
                        talias: aliasName
                    };
                    uidColumnMap[uuuid] = info;

                    query_cache_data.global_uid_column_map[uuuid] = info;
                }

                query_cache_data.line_id_table_column_map[lineId] = uidColumnMap;
            }
            for (var columnUid in uidColumnMap) {

                columns.push({
                    uuid: columnUid,
                    column: uidColumnMap[columnUid]

                });


            }


        }
        return columns;

    }
    function loadSetting() {
        _loadSetting('global_setting', function(rev) {
            var setting = JSON.parse(rev);

            if (typeof setting['data'] !== 'undefined') {
                var data = setting['data'];
                if (typeof data['table_variable_map'] !== 'undefined') {
                    var ss = setting['data']['table_variable_map'];
                    for (var ind in ss) {
                        var vid = ss[ind]['tvm_id'];
                        var vn = ss[ind]['varialbe'];
                        var dbr = ss[ind]['db_name_required'];
                        $('#' + vid + " .varialbe_name").val(vn);
                        $('#' + vid + " .db_name_required").prop('checked', dbr);

                    }
                }

                if (typeof data['setting_custom_header_code'] !== 'undefined') {
                    $('#setting_custom_header_code').val(data['setting_custom_header_code']);
                }
                if (typeof data['setting_custom_tailer_code'] !== 'undefined') {
                    $('#setting_custom_tailer_code').val(data['setting_custom_tailer_code']);
                }

                if (typeof data['setting_error_log_function_name'] !== 'undefined') {
                    $('#setting_error_log_function_name').val(data['setting_error_log_function_name']);
                }
            }
        });


        _loadSetting('definition', function(rev) {
            var setting = JSON.parse(rev);
            if (typeof setting['data'] !== 'undefined') {
                var data = setting['data'];
                if (typeof data['general'] !== 'undefined') {
                    if (typeof data['general']['header'] !== 'undefined') {
                        $('#create_definitions_header').val(data['general']['header']);
                    }
                    if (typeof data['general']['tailer'] !== 'undefined') {
                        $('#create_definitions_tailer').val(data['general']['tailer']);
                    }
                }
            }
        });
    }

    function _loadSetting(subName, callBack) {
        var sn = $('#setting_name').val() + "<?= $this->saved_header ?>";

        var baseUrl = "<?= $this->popUrl('query_builder/load_setting') ?>";
        $.ajax(baseUrl + "?name=" + encodeURIComponent(sn) + "&sub_name=" + encodeURIComponent(subName)).done(function(rev) {

            callBack(rev);

        });
    }

    function showAction() {
        $('.action_div').hide();
        $('#result').hide();
        $('.' + $('#action_select').val()).show();
    }

    function create_post(method, data) {

        console.log(data);
        $.post("<?= $this->popUrl('query_builder/') ?>" + method, data).done(function(reVal) {
            $('#result').val(reVal);
            $('#result').show();
        });
    }

    function create_pdo() {

        var c = 0;
        var dn = null;
        for (var ind in db_table_info) {
            dn = ind;
            c++;
        }
        if (c === 1 && dn !== null) {
            $('#create_class_form .db_name').val(dn);
        }



        var postVal = $('#create_class_form').serialize();
        create_post('create_pdo_connect_code', postVal);
    }

    function collectionGlobalSetting(formId) {

        $('#' + formId + ' .tab_var_map').val(JSON.stringify(table_name_variale_map));
        $('#' + formId + ' .setting_name').val($('#setting_name').val());
        $('#' + formId + ' .setting_custom_header_code').val($('#setting_custom_header_code').val());
        $('#' + formId + ' .setting_custom_tailer_code').val($('#setting_custom_tailer_code').val());
        $('#' + formId + ' .setting_error_log_function_name').val($('#setting_error_log_function_name').val());


    }

    function create_class() {


        populateTableVariableMap();
        collectionGlobalSetting('create_class_form');

        var postVal = $('#create_class_form').serialize();

        create_post('create_class', postVal);

    }

    function create_query() {


        populateTableVariableMap();
        collectionGlobalSetting('create_query_form');



        $('#create_query_form .uid_column_map').val(JSON.stringify(query_cache_data.global_uid_column_map));
        $('#create_query_form .line_id_table_array').val(JSON.stringify(query_cache_data.line_id_table_name_array));
        $('#create_query_form .table_info').val(JSON.stringify(table_info));



        var columns = [];
        $('#query_column_area_column_list input[type="text"]').each(function() {
            columns.push({
                id: $(this).attr('id').replace(/column_alias_/g, ''),
                alias: $(this).val()
            });
        });
        $('#create_query_form .column_data').val(JSON.stringify(columns));

        var tableAlias = {};

        $('#query_select_tables input[class="query_table_alias"]').each(function() {
            tableAlias[$(this).attr('id').replace(/query_table_alias_id_/g, '')] = $(this).val();
        });

        $('#create_query_form .line_id_alias_map').val(JSON.stringify(tableAlias));

        $('#query_select_tables select[class="query_select_join_method"]').each(function() {
            query_cache_data.line_id_logic_map[$(this).attr('id').replace(/query_select_join_method_id_/g, '')].join_type = $(this).val();
        });
        $('#create_query_form .line_id_logic_map').val(lingLogicMap2String());


        $order_by = [];
        $("#query_ordery_by_area .query_order_by_area_one_column").each(function() {

            var type = $(this).find('.query_order_by_type').first().val();

            var cc = {type: type};
            if (type === 'fixed') {


                cc.column_id = $(this).find('.query_order_by_column_id').first().val();
                cc.desc = $(this).find('.query_order_by_desc').first().prop('checked');

            }
            else {
                cc.variable = $(this).find('.query_order_by_column_variable').first().val();


            }

            $order_by.push(cc);
        });
        // order_by_columns
        $('#create_query_form .order_by_columns').val(JSON.stringify($order_by));



        var postVal = $('#create_query_form').serialize();

        create_post('create_query', postVal);

    }
    function create_update() {


        populateTableVariableMap();
        collectionGlobalSetting('create_update_form');
        $('#create_update_form .uid_column_map').val(JSON.stringify(query_cache_data.global_uid_column_map));
        $('#create_update_form .line_id_table_array').val(JSON.stringify(query_cache_data.line_id_table_name_array));
        $('#create_update_form .table_info').val(JSON.stringify(table_info));



        var columns = {};
        $('#update_column_area_column_list input').each(function() {
            var id;
            if ($(this).attr('type') === 'text') {
                id = $(this).attr('id').replace(/update_column_value_/g, '');
            }
            else if ($(this).attr('type') === 'hidden') {
                id = $(this).attr('id').replace(/update_column_type_/g, '');
            }
            else {
                id = $(this).attr('name').replace(/update_column_value_type_/g, '');
            }

            if (typeof columns[id] === 'undefined') {
                columns[id] = {};
            }

            if ($(this).attr('type') === 'text') {
                columns[id]['value'] = $(this).val();
            }
            else if ($(this).attr('type') === 'hidden') {
                columns[id]['data_type'] = $(this).val();
            }
            else if ($(this).attr('type') === 'radio') {
                if ($(this).prop('checked')) {
                    columns[id]['type'] = $(this).val();
                }
            }



        });
        $('#create_update_form .column_data').val(JSON.stringify(columns));

        var tableAlias = {};

        $('#query_select_tables input[class="query_table_alias"]').each(function() {
            tableAlias[$(this).attr('id').replace(/query_table_alias_id_/g, '')] = $(this).val();
        });

        $('#create_update_form .line_id_alias_map').val(JSON.stringify(tableAlias));

        $('#query_select_tables select[class="query_select_join_method"]').each(function() {
            query_cache_data.line_id_logic_map[$(this).attr('id').replace(/query_select_join_method_id_/g, '')].join_type = $(this).val();
        });
        $('#create_update_form .line_id_logic_map').val(lingLogicMap2String());






        var postVal = $('#create_update_form').serialize();

        create_post('create_update', postVal);

    }
    function create_delete() {


        populateTableVariableMap();
        collectionGlobalSetting('create_delete_form');
        $('#create_delete_form .uid_column_map').val(JSON.stringify(query_cache_data.global_uid_column_map));
        $('#create_delete_form .line_id_table_array').val(JSON.stringify(query_cache_data.line_id_table_name_array));
        $('#create_delete_form .table_info').val(JSON.stringify(table_info));


        $('#create_delete_form .line_id_logic_map').val(lingLogicMap2String());


        var postVal = $('#create_delete_form').serialize();

        create_post('create_delete', postVal);

    }
    function create_definitions() {


        populateTableVariableMap();
        collectionGlobalSetting('create_definitions_form');


        var postVal = $('#create_definitions_form').serialize();

        create_post('create_definitions', postVal);

    }


    function create_insert() {


        populateTableVariableMap();
        collectionGlobalSetting('create_insert_form');

        $('#create_insert_form .tab_var_map').val(JSON.stringify(table_name_variale_map));

        $('#create_insert_form .uid_column_map').val(JSON.stringify(query_cache_data.global_uid_column_map));
        $('#create_insert_form .line_id_table_array').val(JSON.stringify(query_cache_data.line_id_table_name_array));
        $('#create_insert_form .table_info').val(JSON.stringify(table_info));



        var columns = {};
        $('#insert_column_area_column_list input').each(function() {
            var id;
            if ($(this).attr('type') === 'text') {
                id = $(this).attr('id').replace(/insert_column_value_/g, '');
            }
            else if ($(this).attr('type') === 'hidden') {
                id = $(this).attr('id').replace(/insert_column_type_/g, '');
            }
            else if ($(this).attr('type') === 'radio') {
                id = $(this).attr('name').replace(/insert_column_value_type_/g, '');
            }
            else if ($(this).attr('type') === 'checkbox') {
                id = $(this).attr('name').replace(/insert_column_value_is_unique_/g, '');
            }

            if (typeof columns[id] === 'undefined') {
                columns[id] = {};
            }

            if ($(this).attr('type') === 'text') {
                columns[id]['value'] = $(this).val();
            }
            else if ($(this).attr('type') === 'radio') {
                if ($(this).prop('checked')) {
                    columns[id]['type'] = $(this).val();
                }
            }
            else if ($(this).attr('type') === 'hidden') {
                columns[id]['data_type'] = $(this).val();
            }

            else if ($(this).attr('type') === 'checkbox' && $(this).prop('checked')) {
                columns[id]['is_unique_index'] = 1;
            }


        });
        $('#create_insert_form .column_data').val(JSON.stringify(columns));

        var tableAlias = {};

        $('#query_select_tables input[class="query_table_alias"]').each(function() {
            tableAlias[$(this).attr('id').replace(/query_table_alias_id_/g, '')] = $(this).val();
        });

        $('#create_insert_form .line_id_alias_map').val(JSON.stringify(tableAlias));

        $('#query_select_tables select[class="query_select_join_method"]').each(function() {
            query_cache_data.line_id_logic_map[$(this).attr('id').replace(/query_select_join_method_id_/g, '')].join_type = $(this).val();
        });
        $('#create_insert_form .line_id_logic_map').val(lingLogicMap2String());






        var postVal = $('#create_insert_form').serialize();

        create_post('create_insert', postVal);

    }

    function lingLogicMap2String() {
        var re = {};
        var tmp = new QueryLogic();
        for (var id in query_cache_data.line_id_logic_map) {
            var d = {};
            var s = query_cache_data.line_id_logic_map[id];

            d.join_type = s.join_type;
            d.logic_data = tmp.removeCircularStructureFromNod(tmp.createLogicNode(null, 0, s.logic_data));
            re[id] = d;
        }
        return JSON.stringify(re);
    }

    var table_name_variale_map = [];
    function populateTableVariableMap() {
        table_name_variale_map = [];
        $('#table_name_variables tr').each(function() {
            var tn = $(this).find('.table_name').val();
            var vn = $(this).find('.varialbe_name').val();
            var dn = $(this).find('.db_name').val();
            var dr = $(this).find('.db_name_required').prop('checked');
            var tvm_id = $(this).find('.tvm_id').val();
            table_name_variale_map.push({
                db: dn,
                table: tn,
                varialbe: vn,
                tvm_id: tvm_id,
                db_name_required: dr
            });

        });


    }

    function getVariableName(originalName) {
        var words = originalName.replace(/\./g, '_');
        return words;
//        var re = "";
//        for (var ind in words) {
//            var one = words[ind];
//            if (one.length === 0) {
//                continue;
//            }
//            if (re === "") {
//                re += one;
//            }
//            else {
//                re += one.substr(0, 1).toUpperCase();
//                if (re.length > 1) {
//                    re += one.substr(1).toLowerCase();
//                }
//            }
//        }
//        return re;
    }
</script>

Action:
<select id="action_select">
    <option value="create_class">Create Class</option>
    <option value="create_query">Create Query</option>
    <option value="create_insert">Create Insert</option>
    <option value="create_update">Create Update</option>
    <option value="create_delete">Create Delete</option>
    <option value="create_definitions">Create Definitions</option>
</select>

<hr/>

<div id="global_setting">
    <h3>Global Setting</h3>

    <table>
        <caption>General</caption>
        <tbody>

            <tr>
                <td>
                    Setting Name
                </td>
                <td>
                    <input value="default" id="setting_name" size="10">
                </td>
            </tr>

            <tr>
                <td>Header Custom Code</td>
                <td>
                    <textarea id='setting_custom_header_code' cols="80"></textarea>
                </td>
            </tr>
            <tr>
                <td>Tailer Custom Code</td>
                <td>
                    <textarea id='setting_custom_tailer_code' cols="80"></textarea>
                </td>
            </tr>


            <tr>
                <td>
                    <span>Error Log Function Name:</span>
                </td>
                <td>
                    <input value="" id="setting_error_log_function_name" size="30">
                </td>
            </tr>


        </tbody>
    </table>


    <table>
        <caption>Table name variables</caption>
        <tbody id="table_name_variables">
            <? foreach ($this->db_table_info as $db => $tables): ?>
                <? foreach ($tables as $tableName => $tmp1): ?>
                    <tr id="tvm_<?= $db ?>_<?= $tableName ?>">
                        <td >
                            <?= $db ?>.<?= $tableName ?>
                            <input type="hidden" value="<?= $db ?>" class="db_name">
                            <input type="hidden" value="<?= $tableName ?>" class="table_name">
                            <input type="hidden" value="tvm_<?= $db ?>_<?= $tableName ?>" class="tvm_id">
                        </td>
                        <td>
                            <input value="<?= strtoupper($db) ?>_<?= strtoupper($tableName) ?>" size="100" class="varialbe_name">
                        </td>

                        <td>
                            <input value="1" type="checkbox" class="db_name_required" checked="checked"> required DB name
                        </td>
                    </tr>

                <? endforeach; ?>
            <? endforeach; ?>
        </tbody>
    </table>

</div>
<hr/>
<div class="action_div create_class">

    <form id="create_class_form">
        <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
        <input class="setting_name" name="setting_name" value="" type="hidden">
        <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
        <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
        <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">

        <input class="db_name" name="db_name" value="" type="hidden">
        <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">

        <table>
            <tbody>
                <tr>
                    <td>Class Name</td>
                    <td><input id="class_name"  name="class_name" class="not_null"></td>
                </tr>
            </tbody>
        </table>
    </form>

    <div class="create_button" style="margin-top: 30px">
        <button id="create_class_bt">Create</button>
    </div>

    <br/>
    <button id="create_pdo_handle_bt">Create PDO</button>



</div>



<div  class="action_div create_query">

    <span>SELECT </span>

    <div id="query_column_area" style="float: none">
        <div id="query_column_area_column_list">

        </div>
        <button id="query_column_area_bt">edit</button>
    </div>

    <span> From </span>
</div>
<div  class="action_div create_delete">

    <span>DELETE </span>



    <span> From </span>
</div>

<div  class="action_div create_update">

    <span>UPDATE </span>


</div>
<div  class="action_div  create_insert">

    <span>INSERT INTO </span>


</div>


<div id='' class="action_div create_query create_update create_delete create_insert">
    <div id="query_tables_area" style="float: none">

        <table>
            <tbody id="query_select_tables">

            </tbody>

        </table>


    </div>



</div>

<div  class="action_div create_update">
    <span>SET  </span>
    <div id="update_column_area" style="float: none">
        <div id="update_column_area_column_list">

        </div>
        <button id="update_column_area_bt">edit</button>
    </div>

</div>
<div  class="action_div create_insert">
    <span>insert values:  </span>
    <div id="insert_column_area" style="float: none">
        <div id="insert_column_area_column_list">

        </div>
        <button id="insert_column_area_bt">edit</button>
    </div>

</div>

<div  class="action_div create_query create_delete create_update">
    <span> WHERE </span>
    <div id="query_where_area" style="float: none">
        <span id="query_on_clause_text_query_where_claus_id"></span>
        <button class="query_where_clause" id="query_where_claus_edit_bt">Edit</button>
    </div>


</div>

<div class="action_div create_query">
    <span> ORDER BY </span>
    <div id="query_ordery_by_area" style="float: none">


    </div>
    <button class="query_order_by_bt" id="query_order_by_add_bt">Add</button>
</div>

<div class="action_div create_query">
    <div class="create_button" style="margin-top: 30px">
        <form id="create_query_form">
            <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
            <input class="setting_name" name="setting_name" value="" type="hidden">
            <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
            <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
            <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">
            <input class="uid_column_map" name="uid_column_map" value="" type="hidden">
            <input class="column_data" name="column_data" value="" type="hidden">
            <input class="line_id_logic_map" name="line_id_logic_map" value="" type="hidden">
            <input class="line_id_table_array" name="line_id_table_array" value="" type="hidden">
            <input class="line_id_alias_map" name="line_id_alias_map" value="" type="hidden">
            <input class="order_by_columns" name="order_by_columns" value="" type="hidden">
            <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">

            <input class="table_info" name="table_info" value="" type="hidden">
            <span>Limit:</span> <span>From(0 base):</span><input class="query_limit_from" name="query_limit_from" value="" type="text">
            <span>Row Number:</span><input class="query_limit_row_number" name="query_limit_row_number" value="" type="text">

            <br/>
            <br/>
            <span> Query Name:</span><input class="query_name" name="query_name" value="" type="text">
            <input type="checkbox" name='query_add_page_function'  value="1">Add Pagination Function

            <input type="checkbox" name='query_return_first_row'  value="1">Return First Row from result
        </form>
        <button id="create_query_bt">Create Query</button>
    </div>
</div>

<div  class="action_div create_update">
    <div class="create_button" style="margin-top: 30px">
        <form id="create_update_form">
            <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
            <input class="setting_name" name="setting_name" value="" type="hidden">
            <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
            <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
            <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">
            <input class="uid_column_map" name="uid_column_map" value="" type="hidden">
            <input class="column_data" name="column_data" value="" type="hidden">
            <input class="line_id_logic_map" name="line_id_logic_map" value="" type="hidden">
            <input class="line_id_table_array" name="line_id_table_array" value="" type="hidden">
            <input class="line_id_alias_map" name="line_id_alias_map" value="" type="hidden">
            <input class="table_info" name="table_info" value="" type="hidden">
            <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">

            Update Function Name:<input class="update_name" name="update_name" value="" type="text">

            <input type="checkbox" id="group_update" name='group_update'  value="1">Group Update
            <input type="checkbox" id="" name='auto_compatiable'  value="1">Auto Compatiable
            <input type="checkbox" id="around_transaction" name='around_transaction'  value="1">Around Transaction

        </form>
        <button id="create_update_bt">Create Update</button>
    </div>

</div>
<div  class="action_div create_insert">
    <div class="create_button" style="margin-top: 30px">
        <form id="create_insert_form">
            <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
            <input class="setting_name" name="setting_name" value="" type="hidden">
            <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
            <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
            <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">
            <input class="uid_column_map" name="uid_column_map" value="" type="hidden">
            <input class="column_data" name="column_data" value="" type="hidden">
            <input class="line_id_logic_map" name="line_id_logic_map" value="" type="hidden">
            <input class="line_id_table_array" name="line_id_table_array" value="" type="hidden">
            <input class="line_id_alias_map" name="line_id_alias_map" value="" type="hidden">
            <input class="table_info" name="table_info" value="" type="hidden">
            <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">

            Insert Function Name:<input class="insert_name" name="insert_name" value="" type="text">
            <input type="checkbox" name='insert_return_last_id'  checked="checked" value="1">Return Last ID
            <input type="checkbox" name='insert_update_method'   value="1">Insert .. on duplicate update method
            <input type="checkbox" id="group_update" name='group_update'  value="1">Group Update
            <input type="checkbox" id="" name='auto_compatiable'  value="1">Auto Compatiable
            <input type="checkbox" id="around_transaction" name='around_transaction'  value="1">Around Transaction
        </form>
        <button id="create_insert_bt">Create Insert</button>
    </div>

</div>

<div  class="action_div create_delete">

    <div class="create_button" style="margin-top: 30px">
        <form id="create_delete_form">
            <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
            <input class="setting_name" name="setting_name" value="" type="hidden">
            <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
            <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
            <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">
            <input class="uid_column_map" name="uid_column_map" value="" type="hidden">
            <input class="column_data" name="column_data" value="" type="hidden">
            <input class="line_id_logic_map" name="line_id_logic_map" value="" type="hidden">
            <input class="line_id_table_array" name="line_id_table_array" value="" type="hidden">
            <input class="line_id_alias_map" name="line_id_alias_map" value="" type="hidden">
            <input class="table_info" name="table_info" value="" type="hidden">
            <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">


            Delete Function Name:<input class="delete_name" name="delete_name" value="" type="text">
            <input type="checkbox" id="group_update" name='group_update'  value="1">Group Update
            <input type="checkbox" id="around_transaction" name='around_transaction'  value="1">Around Transaction

        </form>
        <button id="create_delete_bt">Create Delete</button>
    </div>
</div>

<div  class="action_div create_definitions">

    <div class="create_button" style="margin-top: 30px">
        <form id="create_definitions_form">
            <input class="tab_var_map" name="tab_var_map" value="" type="hidden">
            <input class="setting_name" name="setting_name" value="" type="hidden">
            <input class="setting_custom_header_code" name="setting_custom_header_code" value="" type="hidden">
            <input class="setting_custom_tailer_code" name="setting_custom_tailer_code" value="" type="hidden">
            <input class="setting_error_log_function_name" name="setting_error_log_function_name" value="" type="hidden">
            <input class="saved_header" name="saved_header" value="<?= $this->saved_header ?>" type="hidden">
            <?
            MLog::dExport($this->db_table_info);
            $tableName = "ERROR! can not get table name !!!!";
            $tableDetail = null;
            foreach ($this->db_table_info as $db => $tables) {
                foreach ($tables as $tn => $td) {

                    $tableName = "`{$db}`.`{$tn}`";
                    $tableDetail = $td;
                    break;
                }
                break;
            }
            ?>
            TABLE:<span id="create_definitions_table_name_span">
                <?= $tableName ?>
            </span><br/>
            <input class="create_definitions_table_name" name="create_definitions_table_name" value="<?= $tableName ?>" type="hidden">
            DEFINITION COLUMN:<select name='create_definitions_id_column'>
                <?
                if ($tableDetail !== null) :
                    foreach ($tableDetail as $one):
                        ?>

                        <option value="<?= $one['name'] ?>"><?= $one['name'] ?></option>
                        <?
                    endforeach;
                endif;
                ?>
            </select><br/>
            STATIC VALUE COLUMN:<select name='create_definitions_text_column'>
                <?
                if ($tableDetail !== null) :
                    foreach ($tableDetail as $one):
                        ?>

                        <option value="<?= $one['name'] ?>"><?= $one['name'] ?></option>
                        <?
                    endforeach;
                endif;
                ?>
            </select><br/>

            Header: <input class="create_definitions_header" name="create_definitions_header" id="create_definitions_header" value="" type="text"><br/>
            Tailer: <input class="create_definitions_tailer" name="create_definitions_tailer" id="create_definitions_tailer" value="" type="text"><br/>
            Class Name (Fill this and following map name, if you want generate id=>name Map): 
            <input class="create_definitions_class_name" name="create_definitions_class_name" id="create_definitions_class_name" value="" type="text" size="50"><br/>
            Map Name (if you want generate id=>name Map): 
            <input class="create_definitions_map_name" name="create_definitions_map_name" id="create_definitions_map_name" value="" type="text" size="50"><br/>


        </form>
        <button id="create_definitions_bt">Create Definitions</button>
    </div>
</div>




<hr/>
<textarea id="result" cols="120" rows="50" ></textarea>

<table style="display: none">
    <tbody id="query_select_talbe_template_tr" >
        <tr id="query_select_table_tr_replace_123">
            <td>
                <select  class="query_select_join_method" id="query_select_join_method_id_replace_123">
                    <option>INNER JOIN</option>
                    <option>LEFT JOIN</option>
                    <option>RIGHT JOIN</option>
                    <option>OUTER JOIN</option>

                </select>
            </td>
            <td>
                <select  class="query_select_table" id="query_select_table_id_replace_123">

                </select>
            </td>

            <td>
                Alias:<input type="text" class="query_table_alias" id="query_table_alias_id_replace_123">
            </td>

            <td style="width: 200px">
                <div id="query_on_clause_div_id_replace_123"><span>On: </span>
                    <span id="query_on_clause_text_replace_123" class="query_on_clause_text_span"></span>
                    <button class="query_on_clause" id="query_on_clause_id_replace_123">Edit</button>
                </div>

            </td>

            <td>
                <button id="query_select_table_add_bt_replace_123" class="query_select_table_add_bt">Add one table</button>
            </td>

            <td>
                <button id="query_select_table_delete_bt_replace_123" class="query_select_table_delete_bt">Delete</button>
            </td>

        </tr>
    </tbody>
</table>

<div id="condition_edit_dialog" style="display: none;">
    <div id="condtion_edit_holder">

    </div>

    <hr/>

    <div id="condition_review">

        <textarea id="condtion_review_text" readonly="readonly" cols="80"></textarea>
    </div>

</div>

<div id="select_columns_dialog" style="display: none;">
    <div id="select_columns_holder"></div>


</div>
<div id="order_by_select_columns_dialog" style="display: none;">
    <div id="order_by_select_columns_holder"></div>

    <div>
        <input type="radio" id='order_by_column_user_variable_radio' name="order_by_radio">User's Variable:<input type="text" id='order_by_column_user_variable_name'>
    </div>
</div>
<? include dirname(__FILE__) . '/../share/logic_edit.phtml'; ?>



